package com.ztjava.weixin.controller;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Duang;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Ret;
import com.xiaoleilu.hutool.date.DateUtil;
import com.ztjava.core.Constant;
import com.ztjava.core.annotation.ControllerClass;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.client.PortalClient;
import com.ztjava.ext.auth.annotation.UserController;
import com.ztjava.ext.auth.annotation.UserMethod;
import com.ztjava.ext.auth.bean.AuthSession;
import com.ztjava.plugin.weixin.WeixinKit;
import com.ztjava.plugin.weixin.WeixinSdk;
import com.ztjava.weixin.model.menu.MenuGroup;
import com.ztjava.weixin.model.menu.MenuItem;
import com.ztjava.weixin.service.MenuService;
@ControllerClass(client=PortalClient.class,path="/weixin/menu")
@UserController(portal=Constant.P_PORTAL)
public class MenuPortalController extends BaseController{
	/*************
	 *MenuAdminController.java
	 *@ztjava.com
	 *2018-07-05 14:00:14
	**************/
	private static MenuService menuService = Duang.duang(MenuService.class);
	/*************
	 *修改Group
	**************/
	@UserMethod("WeixinMenu")
	public void addEditGroup(){
		Integer id = getParaToInt("id",0);
		MenuGroup menuGroup = new MenuGroup();
		if(id>0){
			menuGroup = MenuGroup.dao.findById(id);
		}
		setAttr("menuGroup",menuGroup);
		render("addEditGroup.html");
	}

	/*************
	 *保存Group
	**************/
	@UserMethod("WeixinMenu")
	public void saveGroup(){
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		MenuGroup menuGroup = getModel(MenuGroup.class);
		saveModel(menuGroup,authSession.getId());
		renderSuccess();
	}

	/*************
	 *Group列表
	**************/
	@UserMethod("WeixinMenu")
	public void groupList(){
		
		if(!getPara("is_ajax","F").equals("T")){
			keepPara();
			render("groupList.html");
			return;
		}

		
		renderPageJson(menuService.getGroupPage(client, getParaMap()));
	}

	@UserMethod("WeixinMenu")
	public void deleteGroup(){
		Integer id = getParaToInt("id");
		MenuGroup menuGroup = MenuGroup.dao.findById(id);
		if(menuGroup.get("menuid")!=null&&menuGroup.getStr("menuid").equals("")){
			WeixinSdk weixinSdk = WeixinKit.use();
			Ret ret = weixinSdk.menu_delconditional(menuGroup.getStr("menuid"));
			if(ret.getStr(Constant.RESULT).equals(Constant.ERROR)){
				renderError(ret.getStr(Constant.MESSAGE));
				return;
			}
		}
		menuGroup.delete();
		renderSuccess("删除成功");
		return;
	}
	

	@UserMethod("WeixinMenu")
	public void postItem(){
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		Integer group_id = getParaToInt("group_id");
		List<MenuItem> itemList = menuService.getGroupItemList(group_id);
		WeixinSdk weixinSdk = WeixinKit.use();
		if(itemList.size()==0){
			if(group_id>0){
				Ret ret = weixinSdk.menu_delete();
				if(ret.getStr(Constant.RESULT).equals(Constant.ERROR)){
					renderError(ret.getStr(Constant.MESSAGE));
					return;
				}
				//并清空全部个性化菜单配置
				menuService.updateGroupMenuid();
				renderSuccess("默认菜单及个性化菜单已被清空");
				return;
			}else {
				MenuGroup menuGroup = MenuGroup.dao.findById(group_id);
				if(menuGroup.get("menuid")!=null&&menuGroup.getStr("menuid").equals("")){
					Ret ret = weixinSdk.menu_delconditional(menuGroup.getStr("menuid"));
					if(ret.getStr(Constant.RESULT).equals(Constant.ERROR)){
						renderError(ret.getStr(Constant.MESSAGE));
						return;
					}
					menuGroup.set("menuid", null).update();
				}
				renderSuccess("个性化菜单已被清空");
				return;
			}
		}
		JSONObject menu = new JSONObject();
		JSONArray button = new JSONArray();
		for(int i=0;i<itemList.size();i++){
			if(itemList.get(i).getInt("parent_id")>0){
				continue;
			}
			if(itemList.get(i).getStr("type").equals("blank")){
				JSONObject item = new JSONObject();
				item.put("name", itemList.get(i).getStr("name"));
				JSONArray children = new JSONArray();
				for(int j=0;j<itemList.size();j++){
					if(!itemList.get(j).getInt("parent_id").equals(itemList.get(i).getInt("id"))){
						continue;
					}
					children.add(getItemJSON(itemList.get(j)));
				}
				item.put("sub_button", children);	
				button.add(item);
			}else {
				button.add(getItemJSON(itemList.get(i)));
			}
		}
		menu.put("button",button);
		if(group_id>0){
			MenuGroup menuGroup = MenuGroup.dao.findById(group_id);
			JSONObject matchrule = new JSONObject();
			matchrule.put("tag_id", menuGroup.getStr("tag_id"));
			matchrule.put("sex", menuGroup.getStr("sex"));
			matchrule.put("country", menuGroup.getStr("country"));
			matchrule.put("province", menuGroup.getStr("province"));
			matchrule.put("city", menuGroup.getStr("city"));
			matchrule.put("client_platform_type", menuGroup.getStr("client_platform_type"));
			matchrule.put("language", menuGroup.getStr("language"));
			menu.put("matchrule",matchrule);
			Ret ret = weixinSdk.menu_addconditional(menu);
			if(ret.getStr(Constant.RESULT).equals(Constant.ERROR)){
				renderError(ret.getStr(Constant.MESSAGE));
				return;
			}
			menuGroup.set("menuid", ret.getStr("menuid")).set("update_time", DateUtil.now()).set("update_user", authSession.getId()).update();
		}else {
			Ret ret = weixinSdk.menu_create(menu);
			if(ret.getStr(Constant.RESULT).equals(Constant.ERROR)){
				renderError(ret.getStr(Constant.MESSAGE));
				return;
			}
		}
		renderSuccess();
	}
	
	public JSONObject getItemJSON(MenuItem menuItem){
		JSONObject sub = new JSONObject();
		sub.put("name", menuItem.getStr("name"));
		sub.put("type", menuItem.getStr("type"));
		
		switch (menuItem.getStr("type")) {
			case "click":
				sub.put("key", menuItem.getStr("content").trim());
				break;
			case "view":
				sub.put("url", menuItem.getStr("content").trim());
				break;
			case "media_id":
				sub.put("media_id", menuItem.getStr("content").trim());
				break;
			case "view_limited":
				sub.put("media_id", menuItem.getStr("content").trim());
				break;
			default:
				break;
		}
		return sub;
	}
	
	/*************
	 *修改Item
	**************/
	@UserMethod("WeixinMenu")
	public void addEditItem(){
		Integer id = getParaToInt("id",0);
		MenuItem menuItem = new MenuItem();
		if(id>0){
			menuItem = MenuItem.dao.findById(id);
			if(menuItem.getInt("parent_id")>0){
				MenuItem parentItem = MenuItem.dao.findById(menuItem.getInt("parent_id"));
				setAttr("parentItem", parentItem);
			}
		}else{
			Integer parent_id = getParaToInt("parent_id",0);
			menuItem.set("parent_id", parent_id);
			if(parent_id>0){
				MenuItem parentItem = MenuItem.dao.findById(parent_id);
				setAttr("parentItem", parentItem);
			}
			menuItem.set("group_id",getParaToInt("group_id",0));
		}
		setAttr("menuItem",menuItem);
		render("addEditItem.html");
	}

	/*************
	 *保存Item
	**************/
	@UserMethod("WeixinMenu")
	public void saveItem(){
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		MenuItem menuItem = getModel(MenuItem.class);
		if(menuItem.get("id")==null||menuItem.getInt("id")==0){
			Integer amount = menuService.getChildItemAmount(menuItem.getInt("group_id"),menuItem.getInt("parent_id"));
			if(menuItem.getInt("parent_id")==0&&amount>=3){
				renderError("一级菜单最多创建3个菜单");
				return;
			}else if(menuItem.getInt("parent_id")>0&&amount>=5){
				renderError("二级菜单最多创建5个菜单");
				return;
			}
		}
		if(menuItem.getInt("parent_id")>0){
			if(menuItem.getStr("type").equals("blank")){
				renderError("二级菜单不能是根菜单");
				return;
			}
			MenuItem parentItem = MenuItem.dao.findById(menuItem.getInt("parent_id"));
			if(!parentItem.getStr("type").equals("blank")){
				renderError("上级级菜单类型必须是根菜单");
				return;
			}
			if(parentItem.getInt("parent_id")>0){
				renderError("最多只能创建两级菜单");
				return;
			}
		}
		if(!menuItem.getStr("type").equals("blank")){
			if(menuItem.get("content")==null||menuItem.getStr("content").equals("")){
				renderError("内容项请按需填写");
				return;
			}
		}
		saveModel(menuItem,authSession.getId());
		if(menuItem.getInt("parent_id")>0){
			MenuItem parent = MenuItem.dao.findById(menuItem.getInt("parent_id"));
			menuItem.set("num", parent.getStr("num")+menuItem.getInt("id")+",");
		}else {
			menuItem.set("num", menuItem.getInt("id")+",");
		}
		menuItem.update();
		setAttr(Constant.RESULT, Constant.SUCCESS);
		setAttr(Constant.MESSAGE, "保存成功！");
		setAttr("object", menuItem);
		renderJson(new String[]{Constant.RESULT,Constant.MESSAGE,"object"});
	}

	/*************
	 *Item列表
	**************/
	@UserMethod("WeixinMenu")
	public void itemList(){
		Integer group_id = getParaToInt("group_id",0);
		setAttr("group_id",group_id);
		setAttr("listJSON", JsonKit.toJson(menuService.getItemList(group_id)));
		render("itemList.html");
	}

	/*************
	 *删除Item
	**************/
	@UserMethod("WeixinMenu")
	public void deleteItem(){
		Integer id = getParaToInt("id",0);
		if(!menuService.checkChildItem(id)){
			renderError("存在子分类不允许删除！");
			return;
		}
		MenuItem.dao.deleteById(id);
		setAttr(Constant.RESULT, Constant.SUCCESS);
		setAttr(Constant.MESSAGE, "删除成功！");
		setAttr("id", id);
		renderJson(new String[]{Constant.RESULT,Constant.MESSAGE,"id"});
	}

}
